<?php
namespace app\front\logic;
use think\facade\Db;
use app\front\logic\MemberAccountLogic;
use app\front\logic\MemberFromLogic;
use app\front\logic\MemberLogLogic;
use app\common\logic\MailLogic;

class LoginLogic{

	public static $init;
	static function init(){
		if (!isset(self::$init)) {//判断是否以前创建了当前类的实例
            $c = __CLASS__;//获取类名
            self::$init = new static;//如果没有创建，实例化当前类，这里实现类只实例化一次
        }
        return self::$init;//返回类的实例
	}


	//开始登录
	function toLogin(){
		$username = input('username','');
		$password = input('password','');
		if(!$username){
			return ['code'=>104];
		}
		if(!$password){
			return ['code'=>105];
		}
		//查询数据库
		$info = Db::name('member')
				->where('user_name', $username)
				->whereOr('email', $username)
				->find();
		if(!$info){
			return ['code'=>106];
		}

		if($info['status']==99){
			return ['code'=>123];
		}
		// print_r($info);
		$cof = config('app');
		$error_lock_open = $cof['error_lock_open'];
		$error_number = $cof['error_number'];
		$error_time = $cof['error_time'];
		$is_lock = 0;

		if($error_lock_open && $info['is_lock']==1){
			if((time()-strtotime($info['err_time']))/60<$error_time){
				return ['code'=>108];
			}
		}
		// echo (time()-strtotime($info['err_time']))/60;exit;

		//密码验证
		if($info['password']!=md5(md5($password).$info['salt'])){
			if(!$error_lock_open){
				return ['code'=>109];
			}
			//设置错误信息，以及是否需要 锁定账户
			$data = [];
			if($info['err_time'] && time()-strtotime($info['err_time'])>30*60){
				//首选判断时间是否已经超过24小时，如果超过24小时，则重置
				$data['err_times'] = 1;
				$data['is_lock'] = 0;
			}else{
				$data['err_times'] = $info['err_times']+1;
			}
			//错误时间记录
			$data['err_time'] = date('Y-m-d H:i:s');
			if($data['err_times']>=$error_number){
				$data['is_lock'] =	$is_lock  = 1;
			}
			// print_r($data);
			Db::name('member')
				->where('id', $info['id'])
				->update($data);
			if($is_lock==1){
				return ['code'=>108];
			}else{
				return ['code'=>109];
			}

		}
		//确定密码对了，在验证账户是否被锁定了
		if($info['status']!=1){
			return ['code'=>107];
		}
		//密码正确，正常登录
		$token = createToken(64, 'all', 'fr_');
		$data = [];
		$data['err_times'] = 0;
		$data['is_lock'] = 0;
		$data['token'] = $token;
		$data['token_exp'] = date('Y-m-d H:i:s', time()+24*60*60); //过期时间
		Db::name('member')
				->where('id', $info['id'])
				->update($data);
		//登录成功了，写入token值
		return ['code'=>0,'data'=>['token'=>$token,'token_exp'=>$data['token_exp']]];
	}

	//注册
	function toRegister(){
		$username = trim(input('username',''));
		$password = trim(input('password',''));
		$email = trim(input('email',''));
		if(!checkEmail($email)){
			return 121;
		}
		$invitation_code = trim(input('invitation_code',''));

		if(!$username){
			return 104;
		}
		if(!$password){
			return 105;
		}
		if(!$email){
			return 116;
		}
		//查询数据库
		$info = Db::name('member')
				->field('id')
				->where('user_name', $username)
				->whereOr('email', $email)
				->find();
		if($info){
			return 118;
		}

		if($invitation_code){
			$info2 = Db::name('member')
				->field('id')
				->where('invitation_code', $invitation_code)
				->find();
			if(!$info2){
				return 119;
			}
		}

		$data = [];
		$data['user_name'] = $username;
		$data['email'] = $email;
		$data['from_invitation_code'] = $invitation_code;
		$data['salt'] = get_chu(6);
		$data['password'] = md5(md5($password).$data['salt']);
		$data['status'] = 99;
		$data['grade_level'] = 1;
		$data['create_time'] = date('Y-m-d H:i:s');
		$data['invitation_code'] = $this->getUniqidStrs('invitation_code', 8);
		$data['api_key'] = $this->getUniqidStrs('api_key');
		$data['active_code'] = $this->getUniqidStrs('active_code');
		// print_r($data);
		//组合完成，开启事务
		Db::startTrans();
		try {
			//新增
		    $id = Db::name('member')->insertGetId($data);
		    if(!$id){
		    	Db::rollback();
		    	return 120;
		    }
		    // echo 'AAA';
		    // echo $id;
		    //新增用户账户
		    $rs = MemberAccountLogic::addAccount(['member_id'=>$id]);
		    if(!$rs){
		    	Db::rollback();
		    	return 120;
		    }
		    //绑定来源日志
		    if($invitation_code){
		    	$rs1 = MemberFromLogic::init()->bindMember(['member_id'=>$id,'invitation_code'=>$invitation_code]);
		    	if(!$rs1){
			    	Db::rollback();
			    	return 120;
			    }
		    }

		    //记录升级日志
		    $rs3 = MemberLogLogic::addLog($id, 1, 1);
		    if(!$rs3){
		    	Db::rollback();
		    	return 120;
		    }


		    //获取后台邮箱配置
			$mail = Db::name('config')
					->field('name,value')
					->where('type', 6)
					->select();
			$data2 = [];
			foreach($mail as $v){
				$data2[$v['name']] = $v['value'];
			}

			//发送给谁
			$data2['to'] = $email;
			$data2['subject'] = '账号激活';
			$data2['content'] = "账号激活码：".$data['active_code'];

			//发送邮件
			$rs4 = MailLogic::sendEmailMsg($data2);

		    Db::commit();
		    return 0;
		} catch (\Exception $e) {
			// print_r($e->getMessage());
		    // 回滚事务
		    Db::rollback();
		    return 120;
		}
	}

	//找回密码
	function getBackPass(){
		$password = trim(input('password',''));
		$email = trim(input('email',''));
		$code = trim(input('code',''));
		if(!checkEmail($email)){
			return 121;
		}
		if(!$password){
			return 114;
		}
		if(!$code){
			return 124;
		}

		//先验证账号
		$info = Db::name('member')
					->field('id, email, salt, status')
					->where('email', $email)
					->find();
		if(!$info){
			return 106;
		}

		if($info['status']==99){
			return 123;
		}

		if($info['status']!=1){
			return 107;
		}


		//验证验证码
		$cdInfo = Db::name('member_mail_code')
					->where('email', $email)
					->order('id desc')
					->find();
		if($cdInfo['has_used']==1){
			return 127;
		}
		if($cdInfo['available']==0){
			return 126;
		}
		if(time()-strtotime($cdInfo['create_time'])>1800){
			$dd = [];
			$dd['available'] = 0;
			Db::name('member_mail_code')
			->where('id', $cdInfo['id'])
			->update($dd);
			return 126;
		}
		if($cdInfo['code']!=$code){
			//验证码错误了，更新下
			$dd = [];
			$dd['err_times'] = $cdInfo['err_times']+1;
			if($dd['err_times']>=5){
				$dd['available'] = 0;
			}
			Db::name('member_mail_code')
			->where('id', $cdInfo['id'])
			->update($dd);
			// print_r($cdInfo);
			return 125;
		}

		

		Db::startTrans();
		try {
			//验证通过了，开始更改密码
			$dt = [];
			$dt['password'] = md5(md5($password).$info['salt']);
			$dt['token'] = null;
			$rs = Db::name('member')
				->where('id', $info['id'])
				->update($dt);

			$dt2 = [];
			$dt2['has_used'] = 1;
			$dt2['used_time'] = date('Y-m-d H:i:s');
			$rs2 = Db::name('member_mail_code')
					->where('id', $cdInfo['id'])
					->update($dt2);

			if(false===$rs || false===$rs2){
				Db::rollback();
		    	return 128;
			}

			Db::commit();
		    return 0;
		} catch (\Exception $e) {
			print_r($e->getMessage());
		    // 回滚事务
		    Db::rollback();
		    return 128;
		}
	}

	//账号激活
	function accountActive(){
		$active_code = input('active_code', '');
		if(!$active_code){
			return 129;
		}
		$info = Db::name('member')
				->field('id, status, active_code')
				->where('active_code',$active_code)
				->find();
		if(!$info){
			return 130;
		}
		if($info['status']==1){
			return 0;
		}

		if($info['status']==99){
			Db::name('member')->where('id', $info['id'])->update(['status'=>1]);
			return 0;
		}

		return 131;
	}

	//退出登录
	function logout(){
		
	}

	function getUniqidStrs($key='', $len=32){
		if(!$key){
			return '';
		}
		$strs = get_chu($len);
		$rs = Db::name('member')
				->field('id')
				->where($key, $strs)
				->find();
		if($rs){
			$strs = $this->getUniqidStrs($key, $len);
		}

		return $strs;
	}

	//发送邮件
	function sendEmail(){
		$email = trim(input('email',''));
		if(!checkEmail($email)){
			return 121;
		}

		$info = Db::name('member')
					->field('id, email, status')
					->where('email', $email)
					->find();
		if(!$info){
			return 106;
		}

		if($info['status']==99){
			return 123;
		}

		if($info['status']!=1){
			return 107;
		}

		$code = get_chu(6, 'number');
		$md = [];
		$md['code'] = $code;
		$md['member_id'] = $info['id'];
		$md['err_times'] = 0;
		$md['available'] = 1;
		$md['email'] = $email;
		$md['has_used'] = 0;
		$md['create_time'] = date('Y-m-d H:i:s');

		Db::name('member_mail_code')->insert($md);

		//获取后台邮箱配置
		$mail = Db::name('config')
				->field('name,value')
				->where('type', 6)
				->select();
		$data = [];
		foreach($mail as $v){
			$data[$v['name']] = $v['value'];
		}

		
		//发送给谁
		$data['to'] = $email;
		$data['subject'] = '修改密码';
		$data['content'] = "您的验证码是：".$code."，验证码有效期30分钟。";


		if (!MailLogic::sendEmailMsg($data)) {
		    return 122;
		} else {
			return 0;
		}
	}

}